package com.push.notifications;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.content.Context;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;


public class WebServicesTask extends AsyncTask<String, Integer, String> {
	 
	public static final int POST_TASK = 1;
	public static final int GET_TASK  = 2;
	public static final int PUT_TASK  = 3;
	public static final int DEL_TASK  = 4;
	
	
	private static final String TAG = "WebServicesTask";
	private static final int CONN_TIMEOUT = 3000; //3s
	private static final int SOCKET_TIMEOUT = 5000;
	public static boolean bNotReponse = false;
			    
	private int taskType = GET_TASK;
	private Context mContext = null;
	private String processMessage = "Processing ..";
	private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
	private ProgressDialog pDlg = null;	
	
	private boolean bShowLoading;
	
	public static String sData = "";
	public WebServicesTask(int taskType, Context mContext, String processMessage) //nWhat = 0 Root ; =1 SubNew
	{
		this.taskType = taskType;
		this.mContext = mContext;
		this.processMessage = processMessage;	
		this.bShowLoading = false;
	}
	
	public void addNameValuePair(String name, String value )
	{
		params.add(new BasicNameValuePair(name, value));
	}
	
	public void setLoading(boolean bLoading)
	{
		bShowLoading = bLoading;
	}
	private void showProgressDialog() {
		pDlg = new ProgressDialog(mContext);
		pDlg.setMessage(processMessage);
		pDlg.setProgressDrawable(mContext.getWallpaper());
		pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		pDlg.setCancelable(false);
		pDlg.show();
	}
		
	
	private void hideKeyboard() {
		 
        InputMethodManager inputManager = (InputMethodManager) mContext
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        View view = ((Activity)mContext).getCurrentFocus();
        if(view != null)
        {
        	inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            		
        			
        }
        
    }
	
	@Override
   protected void onPreExecute() {
		//hideKeyboard();
      if(bShowLoading)
       showProgressDialog(); 
   }

	 
	@Override
	protected String doInBackground(String... params) {
		// TODO Auto-generated method stub
		String url    = params[0];
		String result = "";
		HttpResponse response = doResponse(url);			
		if( response == null ) {
			if(bShowLoading && pDlg != null)
				pDlg.dismiss();
			bNotReponse = true;
			return result;
		} else {
			try {
				System.out.println("__ checking here __ "); 
				HttpEntity entity = response.getEntity();
				
				if (entity != null) {
					 
	                InputStream instream = entity.getContent();
	                result = inputStreamToString(instream);
	                instream.close();
	            }
				if(bShowLoading && pDlg != null)
					pDlg.dismiss();
				sData = result;	
				if(sData.equals(""))
					bNotReponse = true;
				
           } catch (IllegalStateException e) {
               Log.e(TAG, e.getLocalizedMessage(), e);
               bNotReponse = true;

           } catch (IOException e) {
               Log.e(TAG, e.getLocalizedMessage(), e);
               
           }
		}
		return result;
	}
		
	
	//Establish connection
	private HttpParams getHttpParams()
	{
		System.out.println("__ getHttpParames __ ");
		HttpParams http = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(http, CONN_TIMEOUT);
		HttpConnectionParams.setSoTimeout(http, SOCKET_TIMEOUT);
		return http;
	}
	
	private HttpResponse doResponse( String url )
	{
		HttpClient httpClient = new DefaultHttpClient(getHttpParams());
		HttpResponse response = null;
		try {
           switch (taskType) { 
           case POST_TASK:
               HttpPost httppost = new HttpPost(url);
               // Add parameters
               httppost.setEntity(new UrlEncodedFormEntity(params));

               response = httpClient.execute(httppost);
               break;
           case GET_TASK:
           	HttpGet httpget = new HttpGet(url);
               response = httpClient.execute(httpget);
               break;
           case PUT_TASK:
           	break;
           case DEL_TASK:   
        	   HttpDelete httpDel = new HttpDelete(url);
        	   response = httpClient.execute(httpDel);
           	break;
           }
           
       } catch (Exception e) {

           Log.e(TAG, e.getLocalizedMessage(), e);

       }
       return response;
	}
	
	 private String inputStreamToString(InputStream is) {
		 
           String line = "";
           StringBuilder total = new StringBuilder();

           // Wrap a BufferedReader around the InputStream
           BufferedReader rd = new BufferedReader(new InputStreamReader(is), 8192);

           try {
               // Read response until the end
               while ((line = rd.readLine()) != null) {
                   total.append(line);
               }
           } catch (IOException e) {
               Log.e(TAG, e.getLocalizedMessage(), e);
           }

           // Return full string
           return total.toString();
       }
		
}  
